<template>
  <div>
    <div class="header">
      <el-page-header @back="goBack">
        <template #content>
          <span class="route"> {{ title }} </span>
          <span class="route" style="color:#999">  {{ active }} </span>
          <el-button
            type="primary" class="ml20"
            size="small"
            @click="addCollect"
          >
            新增汇总
          </el-button>
          <el-button
            type="warning" class="ml20"
            size="small"
            @click="saveAll"
          >
            保存所有
          </el-button>
        </template>
      </el-page-header>
    </div>
    <div v-loading="loading&&!editControlCommon.isShow&&!editFiledCommon.isShow&&!selectTableData.isShow" class="detail">
      <el-card class="box-card" shadow="hover">
        <template #header>
          <div class="card-header ">
            基本信息
          </div>
        </template>
        <div style="display:flex;align-items:center" class="mb10">
          汇总计划名称：
          <el-tag type="info" class="ml10 mr20">
            {{ detail?.collectSchemeName }}
          </el-tag>

          汇总计划描述：
          <el-tag type="info" class="ml10 mr20">
            {{ detail?.collectSchemeDesc }}
          </el-tag>

          汇总日期： <el-tag type="info" class="ml10 mr20">
            {{ detail?.timeFormula?.join(' 至 ') }}
          </el-tag>

          汇总类型：
          <el-tag type="info" class="ml10 mr20">
            {{ detail?.collectObject==='BILL'?'汇总原始账单':'二次汇总' }}
          </el-tag>

          账单类型：

          <el-tag type="info">
            {{ detail?.billType==='COST'?'应收':'应付' }}
          </el-tag>
        </div>
      </el-card>
    </div>

    <div v-loading="loading&&!editControlCommon.isShow&&!editFiledCommon.isShow&&!selectTableData.isShow" class="detail">
      <el-card
        v-for="(item,idx) in dataList" :key="item.schemeCode"
        class="mb30"
        shadow="hover"
      >
        <template #header>
          <div class="card-header ">
            <div class="inline-block  mr20 flex-center">
              <el-popover
                placement="top"
                width="300"
                effect="dark"
                :hide-after="0"
              >
                <template #reference>
                  <el-icon style="color:rgb(255, 0, 0)">
                    <Warning />
                  </el-icon>
                </template>
                <template #default>
                  哪个方案生成的账单数据需要汇总
                </template>
              </el-popover>
              <span class="ml6">
                汇总的账单：
              </span>
              <el-tag type="success">
                {{ item.schemeName }}
              </el-tag>
            </div>
            <div class="inline-block mr20 flex-center">
              <el-popover
                placement="top"
                width="300"
                effect="dark"
                :hide-after="0"
              >
                <template #reference>
                  <el-icon style="color:rgb(255, 0, 0)">
                    <Warning />
                  </el-icon>
                </template>
                <template #default>
                  哪个时间段的账单需要汇总，这个时间段去哪个数据的值
                </template>
              </el-popover>
              <span class="ml6">
                时间限制字段：
              </span>
              <el-tag type="success">
                {{ item.timeFieldName }}
              </el-tag>
            </div>
          </div>
        </template>
        <div>
          <el-tag
            v-for="(tag,index) in item.schemeDetailList"
            :key="tag.id"
            class="mr20"
            closable
            size="large"
            :disable-transitions="false"
            style="cursor:pointer"
            @close="handleClose(tag,item,index)"
            @click="showDeital(tag,idx,index)"
          >
            {{ tag.schemeResultName }} 汇总成--> {{ tag.collectResultName }}
          </el-tag>
          <el-button
            type="primary"
            text
            @click="addField('schemeDetail',item,idx)"
          >
            + 新增字段
          </el-button>
        </div>
      </el-card>
    </div>
    <selectDialogForm
      v-if="editControlCommon.isShow"
      ref="dialogForm"
      :width="'42%'"
      :loading="loading"
      :form-data="formData"
      :is-show="editControlCommon.isShow"
      :title="'请填写相关信息'"
      :form-input-el="editControlCommon.formInputEl"
      :form-select-el="editControlCommon.formSelectEl"
      :form-text-area-el="editControlCommon.formTextAreaEl"
      :form-upload-el="editControlCommon.formUploadEl"
      :form-time-and-number="editControlCommon.formTimeAndNumber"
      @close-dialog="editControlCommon.isShow=false"
      @emit-open-dialog="editControlCommon.emitOpenDialog"
      @input-done="editControlCommon.inputDone"
    />
    <selectDialogForm
      v-if="editFiledCommon.isShow"
      ref="dialogFormFiled"
      :width="'42%'"
      :loading="loading"
      :form-data="filedData"
      :is-show="editFiledCommon.isShow"
      :title="'请填写相关信息'"
      :form-input-el="editFiledCommon.formInputEl"
      :form-select-el="editFiledCommon.formSelectEl"
      :form-text-area-el="editFiledCommon.formTextAreaEl"
      :form-upload-el="editFiledCommon.formUploadEl"
      :form-time-and-number="editFiledCommon.formTimeAndNumber"
      @close-dialog="editFiledCommon.isShow=false"
      @emit-open-dialog="editFiledCommon.emitOpenDialog"
      @input-done="editFiledCommon.inputDone"
    />
    <selectDialogTable
      v-if="selectTableData.isShow"
      ref="dialogSearch"
      :use-choose="false"
      :append-table-style="{ background: '#126f9e', color: '#fff', borderColor: 'rgba(192, 192, 192,.5)' }"
      :width="'60%'"
      :search-input-placeholder="selectTableData.searchPlaceholde"
      :is-show="selectTableData.isShow"
      :data-source="selectTableData.dataSource"
      :title="'选择数据'"
      is-show-search-input
      :loading="loading"
      @close-dialog="selectTableData.isShow=false"
      @do-dialog-search="selectTableData.doSearch"
      @choose-row="selectTableData.chooseRow"
    />
  </div>
</template>

<script setup>
import { pbRequest } from "@/applications/sys/public/pbRequest/index"
import selectDialogTable from '@/components/public/selectDialogTable.vue'
import selectDialogForm from '@/components/public/selectDialogForm.vue'
import { ref, onBeforeMount, getCurrentInstance, reactive } from "vue"
import { useRouter, useRoute } from 'vue-router'
import { DataSource, loading } from '../utils/summaryPlan'

const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()
const title = ref(`首页 / 汇总计划明细 / `)
const active = ref(`${route.query.title}`)

const goBack = () => {
  if (clickSave){
    router.go(-1)
    return
  }
  proxy.$alert('即将离开当前编辑页，未保存的数据将失效', '提示', {
    confirmButtonText: '确认离开',
    type: 'warning',
    icon: 'InfoFilled',
    callback: (action) => {
      if (action === 'confirm') {
        router.go(-1)
      }
    }
  })

}
const dataSource = ref(null)
const initData = async () => {
  await dataSource.value.initData(this, proxy.$refs.table)

  // collectResultCode
  // collectResultName
  // schemeCode
  // schemeName
  // id

  let res = []
  let testKey = {}
  dataSource.value.tableData.forEach((item, idx) => {
    if (!testKey.hasOwnProperty(item.schemeCode)){
      testKey[item.schemeCode] = res.length
      res.push({
        schemeName: item.schemeName,
        schemeCode: item.schemeCode,
        timeFieldName: item.timeFieldName,
        timeField: item.timeField,
        schemeDetailList: [{
          collectResultCode: item.collectResultCode,
          collectResultName: item.collectResultName,
          schemeResultCode: item.schemeResultCode,
          schemeResultName: item.schemeResultName,
          collectType: item.collectType,
          id: item.id
        }]
      })
    } else {
      res[testKey[item.schemeCode]].schemeDetailList.push({
        collectResultCode: item.collectResultCode,
        collectResultName: item.collectResultName,
        schemeResultCode: item.schemeResultCode,
        schemeResultName: item.schemeResultName,
        collectType: item.collectType,
        id: item.id
      })
    }
  })
  dataList.length = 0
  dataList.push(...res)
}

const detail = ref(null)

let forMatTimeFormula = (value1) => {
  let now = new proxy.$DataTool().timeStamp2Time(Date.parse(new Date())).split('-')
  let value = value1.toString().split('.')

  if (Number(now[1]) - Math.abs(Number(value[0])) <= 0){
    now[0] = now[0] - Math.abs(Number(now[1]) - Math.abs(Number(value[0])))
  }
  return now[0] + '-' + (Number(now[1]) - Math.abs(Number(value[0]))).toString().padStart(2, '0') + '-' + value[1].toString().padStart(2, '0')
}

onBeforeMount(() => {
  dataSource.value = new DataSource({
    modules: 'summaryPlan',
    selectUri: '/colorful-fog/CollectSchemeDetail/select'
  })

  dataSource.value.getMainDetail(route.query.id).then(res => {
    if (res.code === 200){
      detail.value = res.data.pageInfo.list[0]
      detail.value.timeFormula = [forMatTimeFormula(detail.value.timeFormulaStart), forMatTimeFormula(detail.value.timeFormulaEnd)]
    }
  })

  dataSource.value.searchData = { collectSchemeCode: route.query.collectSchemeCode }
  initData()

})

// "collectSchemeCode": "string",
//   "collectType": "SUM",
//   "schemeCode": "string",
//   "schemeName": "string",

const dataList = reactive([])

const addCollect = () => {
  formData.value = {}
  editControlCommon.isShow = true
}

const formData = ref({})

const editControlCommon = reactive({
  isShow: false,
  formInputEl: [{
    title: "汇总的账单",
    key: 'schemeName',
    element: 'input',
    type: 'dialog',
    rules: [{
      required: true,
      message: '该项不能为空',
      trigger: 'blur'
    }]
  }, {
    title: "时间限制字段",
    key: 'timeFieldName',
    element: 'input',
    type: 'dialog',
    rules: [{
      required: true,
      message: '该项不能为空',
      trigger: 'blur'
    }]
  }],
  formSelectEl: [],
  formTextAreaEl: [],
  formTimeAndNumber: [],
  emitOpenDialog: (val) => {
    openSelectDialog(val)
  },
  inputDone: (val) => {

    // 找一下有没有相同的账单

    let idx = dataList.findIndex(item => item.schemeCode === val.schemeCode)
    if (idx !== -1){
      proxy.$message.error('该账单方案已经添加过了')
      return
    }
    dataList.push({
      schemeCode: val.schemeCode,
      schemeName: val.schemeName,
      collectType: val.collectType,
      timeFieldName: val.timeFieldName,
      timeField: val.timeField,
      schemeDetailList: []

    })
    editControlCommon.isShow = false
  }
})

const filedData = ref({})
const editFiledCommon = reactive({
  isShow: false,
  formInputEl: [{
    title: "原账单字段",
    key: 'schemeResultName',
    element: 'input',
    type: 'dialog',
    rules: [{
      required: true,
      message: '该项不能为空',
      trigger: 'blur'
    }]
  }, {
    title: "汇总后字段名称",
    key: 'collectResultName',
    element: 'input',
    rules: [{
      required: true,
      message: '该项不能为空',
      trigger: 'blur'
    }]
  }, {
    title: "字段类型",
    key: 'collectType',
    element: 'radio',
    options: [{
      label: '所有相关字段相加',
      value: 'SUM'
    }, {
      label: '只取一行中的数据',
      value: 'ONE'
    }],
    rules: [{
      required: true,
      message: '该项不能为空',
      trigger: 'blur'
    }]
  }],
  formSelectEl: [],
  formTextAreaEl: [],
  formTimeAndNumber: [],
  emitOpenDialog: (val) => {
    openSelectDialog(val, editFiledCommon.append)
  },
  inputDone: (val) => {

    if (val.id)
      dataList[editFiledCommon.index].schemeDetailList[editFiledCommon.chilIndex] = val
    else dataList[editFiledCommon.index].schemeDetailList.push(val)
    editFiledCommon.isShow = false
  }
})

const addField = (type, item, index) => {
  editFiledCommon.isShow = true
  editFiledCommon.append = item
  editFiledCommon.index = index
  filedData.value = {}
}

const openSelectDialog = async (val, append) => {
  selectTableData.useChoose = true
  switch (val){

  case 'schemeName': {
    selectTableData.searchPlaceholde = '输入账单计划名称进行搜索'
    selectTableData.chooseRow = (val) => {

      proxy.$refs.dialogForm.updateDialogInput({ schemeName: val.name, schemeCode: val.schemeCode })
      formData.value.schemeCode = val.schemeCode
      selectTableData.isShow = false
    }
    selectTableData.doSearch = (val) => {
      selectTableData.dataSource.searchData = { }
      if (val) selectTableData.dataSource.searchData.name = val
      selectTableData.dataSource.initData()
    }
    selectTableData.dataSource = new DataSource({
      selectUri: `/colorful-fog/schemeMain/selectMenu`,
      tableHeader: [{
        label: "账单名称",
        prop: "name",
        width: 200
      }, {
        label: "账单code",
        prop: "schemeCode",
        width: 200
      }, {
        label: "类型",
        prop: "billType",
        width: 200
      }],
      pageSize: 10
    })

    selectTableData.dataSource.forMatData = (row, column) => {
      if (column.property === 'billType') return row[column.property] === 'PAY' ? '应付' : '应收'
      return row[column.property] ?? '-'
    }
    selectTableData.dataSource.initData = async (context = selectTableData.dataSource) => {
      let { data: { data, code, message } } = await pbRequest.post(`${context.selectUri}?currentPage=${context.currentPage}&pageSize=${context.pageSize}`, context.searchData)
      if (code !== 200) return
      selectTableData.dataSource.tableData.length = 0
      selectTableData.dataSource.tableData.push(... data['仓储费用计划'])
      selectTableData.dataSource.tableData.push(... data['物流费用'])

      selectTableData.dataSource.total = selectTableData.dataSource.tableData.length
    }
    await selectTableData.dataSource.initData()
    selectTableData.isShow = true
    return
  }

  case 'timeFieldName':
  case 'schemeResultName': {
    selectTableData.useChoose = false
    selectTableData.searchPlaceholde = '输入字段名称进行搜索'
    selectTableData.chooseRow = (selectVal) => {
      if (val === 'schemeResultName') proxy.$refs.dialogFormFiled.updateDialogInput({ schemeResultName: selectVal.resultName, schemeResultCode: selectVal.resultCode, collectResultName: selectVal.resultName })
      if (val === 'timeFieldName') proxy.$refs.dialogForm.updateDialogInput({ timeFieldName: selectVal.resultName, timeField: selectVal.resultCode })
      selectTableData.isShow = false
    }
    selectTableData.doSearch = (val) => {
      selectTableData.dataSource.searchData = { schemeCode: append ? append.schemeCode : formData.value.schemeCode }
      if (val) selectTableData.dataSource.searchData.resultName = val
      selectTableData.dataSource.initData()
    }
    selectTableData.dataSource = new DataSource({
      selectUri: `/colorful-fog/schemeDetail/select`,
      tableHeader: [{
        label: "字段名称",
        prop: "resultName",
        width: 200
      }, {
        label: "字段Code",
        prop: "resultCode",
        width: 200
      }, {
        label: "字段类型",
        prop: "type",
        width: 200
      }],
      pageSize: 10
    })
    selectTableData.dataSource.searchData = { schemeCode: append ? append.schemeCode : formData.value.schemeCode }
    selectTableData.dataSource.forMatData = (row, column) => {
      if (column.property === 'type') return fieldType[row[column.property]]
      return row[column.property] ?? '-'
    }
    await selectTableData.dataSource.initData()
    selectTableData.isShow = true
    return

  }

  default: {
    return
  }
  }
}

const fieldType = {
  'FIXED': '固定系数',
  'ORDER_DATA': '原单据字段值',
  'DEPEND': '分类系数',
  'EQUATION': '自定义公式'
}

const selectTableData = reactive({
  isShow: false,
  dataSource: null,
  searchPlaceholde: '',
  doSearch: (val) => {
    console.log(val)
  },
  chooseRow: (val) => {
    console.log(val)
  }
})
let clickSave = false

const handleClose = (tag, item, index) => {
  if (!tag.id){
    item.schemeDetailList.splice(index, 1)
    return
  }
  if (item.schemeDetailList.length === 1){
    proxy.$alert('已经是最后一个字段了，确认删除请点继续！', '提示', {
      type: 'error',
      icon: 'InfoFilled',
      confirmButtonText: '继续',
      callback: action => {
        if (action === 'confirm') {
          dataSource.value.deleteCollectDetails([tag.id]).then(res => {
            if (res.code === 200){
              proxy.$message.success('删除成功')
              initData()
            }
          })
        }
      }
    })
    return
  }
  proxy.$alert('是否确认删除当前字段？', '提示', {
    type: 'error',
    icon: 'InfoFilled',
    confirmButtonText: '确定',
    callback: action => {
      if (action === 'confirm') {
        dataSource.value.deleteCollectDetails([tag.id]).then(res => {
          if (res.code === 200){
            proxy.$message.success('删除成功')
            initData()
          }
        })
      }
    }
  })
}

const showDeital = (item, index, chilIndex) => {
  filedData.value = { ...item }
  editFiledCommon.chilIndex = chilIndex
  editFiledCommon.index = index
  editFiledCommon.isShow = true

}

const saveAll = () => {

  proxy.$alert('是否确认保存？', '提示', {
    type: 'info',
    icon: 'InfoFilled',
    confirmButtonText: '确定',
    callback: (action) => {
      if (action === 'confirm') {
        clickSave = true
        let paramsAdd = []
        let paramsUpdate = []
        dataList.forEach(val => {
          let adds = val.schemeDetailList.filter(i => !i.id) // 找到需要新增的
          let updates = val.schemeDetailList.filter(i => i.id) // 找到需要更新的
          paramsAdd.push(...adds.map(item => {
            return {
              collectSchemeCode: route.query.collectSchemeCode,
              schemeCode: val.schemeCode,
              schemeName: val.schemeName,
              timeFieldName: val.timeFieldName,
              timeField: val.timeField,
              collectType: item.collectType,
              collectResultName: item.collectResultName,
              schemeResultCode: item.schemeResultCode,
              schemeResultName: item.schemeResultName
            }
          }))

          paramsUpdate.push(...updates.map(item => {
            return {
              id: item.id,
              collectSchemeCode: route.query.collectSchemeCode,
              schemeCode: val.schemeCode,
              schemeName: val.schemeName,
              timeFieldName: val.timeFieldName,
              timeField: val.timeField,
              collectType: item.collectType,
              collectResultName: item.collectResultName,
              collectResultCode: item.collectResultCode,
              schemeResultCode: item.schemeResultCode,
              schemeResultName: item.schemeResultName
            }
          }))
        })
        if (paramsAdd.length !== 0){
          dataSource.value.addCollectDetails(paramsAdd).then(res => {
            if (res.code === 200){
              proxy.$notify({
                title: '执行了新增操作',
                message: '新增成功',
                type: 'success'
              })
              initData()
              return
            }
          })
        }
        if (paramsUpdate.length !== 0){
          dataSource.value.updateCollectDetails(paramsUpdate).then(res => {
            if (res.code === 200){
              proxy.$notify({
                title: '执行了更新操作',
                message: '更新成功',
                type: 'success'
              })
              initData()
              return
            }
          })
        }
      }
    }
  })

}
</script>

<style lang="less" scoped>
.detail{
  margin-top: 6px;
  font-size: 14px;
  padding: 10px 20px;
}
.header{
  padding: 20px;
  background: #fff;
}
.route{
  font-size: 14px;
  font-weight: 500;
  color: #252525;
  letter-spacing: 1px;
  cursor: default;
}
.table{

  overflow-x: hidden;
  margin-top: 10px;
}
:deep(.is-active){
  background: #ecf5ff;
}
.demo-tabs{
  width: 150px;
}

:deep(.show-detail){
  font-size: 12px;
  color:#22a6f2;
  cursor: pointer;
}

.card-header{
  display: flex;
  align-items: center;
}
</style>